package com.stylefeng.guns.modular.pay.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.modular.pay.dao.AliyunSmsMapper;
import com.stylefeng.guns.modular.pay.exception.BusException;
import com.stylefeng.guns.modular.pay.model.AliyunSms;
import com.stylefeng.guns.modular.pay.service.IAliyunSmsService;
import com.stylefeng.guns.modular.pay.util.AlipaySmsUtil;
import com.stylefeng.guns.modular.pay.util.RandomUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-09-07
 */
@Service
public class AliyunSmsServiceImpl extends ServiceImpl<AliyunSmsMapper, AliyunSms> implements IAliyunSmsService {
	@Autowired
	private AliyunSmsMapper aliyunSmsMapper;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	
	@Override
	public String sendSms(String phone) {
		//短信配置信息获取
		AliyunSms aliyunSms = aliyunSmsMapper.selectById(1);
		String code = RandomUtil.getRandom(4);
		redisTemplate.boundHashOps(Const.SMS_CODE).put(phone, code);
		SendSmsResponse res = null;
		try {
			 res = AlipaySmsUtil.sendSms(aliyunSms,phone,code);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		if(res.getCode() != null && res.getCode().equals("OK")){
			return code;
		}else{
			throw new BusException(res.getMessage());
		}
	}

}
